<?php
namespace app\admin\controller;
use app\common\model\ZhiyuanCard as ZhiyuanCardModel;
use app\common\model\ZhiyuanCardRed as ZhiyuanCardRedModel;
use think\facade\Request;
use think\validate;
use think\Db;
use PHPExcel\PHPExcel;

class ZhiyuanCard extends Base
{
    
    public function index(){
		
		$data['kw'] = input('kw');
		$data['Nowpage'] = input('get.page') ? input('get.page'):1;
		
		$map['status'] = 1;
		if($data['kw']&&$data['kw']!==""){
			$map['title'] = ['like',"%" . $data['kw'] . "%"];
		}
		$list = ZhiyuanCardModel::where($map)->order('id asc')->paginate(config('list_rows'))->toArray();
		$data['count'] = $list['total'];
		$data['allpage'] = $list['last_page'];  
		$user_date = $list['data'];
		
		if(input('get.page')){
			return json($user_date);
		}
		$this->assign($data);
		return $this->fetch();
    }
	
    public function edit(){
       if ($this->request->isPost()) {
            $data = $this->request->post();
			$validate = validate('Common');
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			if ($data['id']) {//编辑
                $res = ZhiyuanCardModel::update($data, ['id' => $data['id']]);
                if ($res) {
                    $this->success('编辑成功');
                } else {
                    $this->error('编辑失败');
                }
            } else {//添加
                $obj = new ZhiyuanCardModel;
                $res = $obj->allowField(true)->save($data);
                if ($res) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
        } else {
            $id = $this->request->param('id', 0, 'intval');
            if ($id) {
                $list = ZhiyuanCardModel::where('id', '=', $id)->find();
            }else{
				$list = ['valid_type'=>1];
            }
            return $this->fetch('',['list'=>$list]);
        } 
        
    }
	
	public function generate(){
       if ($this->request->isPost()) {
            $data = $this->request->post();
			$validate = validate('Common');
			if (empty($data['id'])) {
				$this->error('缺少id参数');
			}
			if (empty($data['nums'])) {
				$this->error('请输入生成数量');
			}
			$list = ZhiyuanCardModel::where('id', '=', $data['id'])->find();
			if (empty($list)) {
				$this->error('志愿卡不存在');
			}
			$nums = (int)$data['nums'];
			$dataI = [];
			$create_time = time();
			Db::startTrans();
			for($i=0;$i<$nums;$i++){
				$card_no = ZhiyuanCardModel::GeneCardNo('',date('y',strtotime('+1 year')));
				$card_passwd = ZhiyuanCardModel::GeneCardPwd('',8);
				$dataI[] = ['valid_type'=>$list['valid_type'],'card_id'=>$data['id'],'title'=>$list['title'],'pici'=>$data['pici'],'valid_days'=>$list['valid_days'],'valid_date'=>$list['valid_date'],'card_no'=>$card_no,'card_passwd'=>$card_passwd,'create_time'=>$create_time];
			}
			
			$flag = Db::name('zhiyuan_card_red')->limit(100)->insertAll($dataI);
			
			if ($flag !== false) {
				Db::commit();
				$this->success('生成成功');
			} else {
				Db::rollback();
				$this->error('生成失败1');
			}
        } else {
            $id = $this->request->param('id', 0, 'intval');
            if ($id) {
                $list = ZhiyuanCardModel::where('id', '=', $id)->find();
            }else{
				$this->error('失败');
            }
            return $this->fetch('',['list'=>$list]);
        } 
        
    }
	
    public function del(){
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
			$res = ZhiyuanCardModel::where('id',$id)->delete();
			if ($res) {
				$this->success('删除成功');
			}else {
				$this->error('删除失败');
			}
        } else {
            $this->error('参数错误');
        }
        
    }
    
	//志愿卡卡密
	public function card_red(){
		
		$data['kw'] = input('kw');
		$data['pici'] = input('pici');
		$data['Nowpage'] = input('get.page') ? input('get.page'):1;
		
		$map['status'] = 1;
		if($data['kw'] && $data['kw']!==""){
			$map['title'] = ['like',"%" . $data['kw'] . "%"];
		}
		if(!empty($data['pici'])){
			$map['pici'] = ['like',"%" . $data['pici'] . "%"];
		}
		$list = ZhiyuanCardRedModel::where($map)->order('id desc')->paginate(config('list_rows'))->toArray();
		foreach($list['data'] as $k=>$v)
        {
			$list['data'][$k]['valid_days'] = ($v['valid_type']==2)?'高考年份9月1号':(($v['valid_type']==3)?$v['valid_date']:$v['valid_days'].'天');
            $list['data'][$k]['valid_time'] = $v['valid_time']?date('Y-m-d H:i:s',$v['valid_time']):'';
			$list['data'][$k]['use_realname'] = '';
			$list['data'][$k]['use_phone'] = '';
			if($v['is_used'] == 1){
				$member = Db::name('member')->where('id',$v['user_id'])->field('realname,phone')->find();
				$list['data'][$k]['use_realname'] = $member['realname'];
				$list['data'][$k]['use_phone'] = '('.$member['phone'].')';
			}
        }
		$data['count'] = $list['total'];
		$data['allpage'] = $list['last_page'];  
		$user_date = $list['data'];
		
		if(input('get.page')){
			return json($user_date);
		}
		$this->assign($data);
		return $this->fetch();
    }

	public function card_red_export(){
		
		$data['kw'] = input('kw');
		$data['pici'] = input('pici');
		
		$map['status'] = 1;
		if($data['kw'] && $data['kw']!==""){
			$map['title'] = ['like',"%" . $data['kw'] . "%"];
		}
		if(!empty($data['pici'])){
			$map['pici'] = ['like',"%" . $data['pici'] . "%"];
		}
		$list = Db::name('zhiyuan_card_red')->where($map)->order('id asc')->select();
		$arr = [];
		foreach($list as $k=>$v)
        {
			$valid_days = ($v['valid_type']==2)?'高考年份9月1号':(($v['valid_type']==3)?$v['valid_date']:$v['valid_days'].'天');
            $valid_time = $v['valid_time']?date('Y-m-d H:i:s',$v['valid_time']):'';
			$use_realname = '';
			$use_phone = '';
			if($v['is_used'] == 1){
				$member = Db::name('member')->where('id',$v['user_id'])->field('realname,phone')->find();
				$use_realname = $member['realname'];
				$use_phone = '('.$member['phone'].')';
			}
			$arr[$k] = [$v['id'],$v['card_no'],$v['card_passwd'],$v['title'],$v['pici'],$valid_days,$v['is_used']?'已被使用':'未使用',$use_realname.$use_phone,date('Y-m-d H:i:s',$v['create_time']),$valid_time];
        }
		$config = [
            'path' => './uploads/daochu' // xlsx文件保存路径
        ];
        $excel  = new \Vtiful\Kernel\Excel($config);
        $filePath = $excel->fileName('卡密导出.xlsx', 'sheet1')
            ->header(['ID','卡号', '密码','名称','批次','有效期','是否被使用','使用人','添加时间','到期时间'])
            ->data($arr)
            ->output();   
        return redirect('/uploads/daochu/卡密导出.xlsx'); 
    }
	
    public function del_red(){
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
			$res = ZhiyuanCardRedModel::where('id',$id)->delete();
			if ($res) {
				$this->success('删除成功');
			}else {
				$this->error('删除失败');
			}
        } else {
            $this->error('参数错误');
        }
	}	
        
}




?>